/**
* @file  HoverMask 组件编辑器hover遮罩
* @author xiao_xie
* @date 2025-03-18
*/


import classNames from 'classnames';
import React, { useCallback, useEffect, useMemo } from 'react';
import useComponentStore, { findComponentById } from '../../../store';
import { Popconfirm } from 'antd';
import { createPortal } from 'react-dom';
interface Props {
    componentId: string | number; // 组件dom的id
    componentWrapper: string; // 组件的wrapper的class
    maskWrapper: string; // 要渲染dom组件的wrapper的calss
}

interface PositionType {
    top: number;
    left: number;
    width: number;
    height: number;
}

const ClickMask: React.FC<Props> = ({ componentId, componentWrapper, maskWrapper }) => {

    const [position, setPosition] = React.useState<PositionType>({ top: 0, left: 0, width: 0, height: 0 }) // 组件的位置
    const { components, removeComponent, setCurComponent } = useComponentStore();

    // 根据id查找组件，获取组件的描述
    const curComponet = useMemo(() => findComponentById(Number(componentId), components), [componentId])


    const handlePositsion = useCallback(() => {
        const elem = document.querySelector(`[data-component-id="${componentId}"]`);
        const wrapper = document.querySelector(`.${componentWrapper}`);

        if (!wrapper) return;
        const { left: warpperLeft, top: warpperTop } = wrapper.getBoundingClientRect();
        if (elem) {
            const { width, height, left, top } = elem.getBoundingClientRect();
            setPosition({
                width, height,
                left: left - warpperLeft,
                top: top - warpperTop
            })
        }
    }, [componentWrapper, componentId, components])

    useEffect(() => {
        handlePositsion();
        const resizeHandler = () => {
            setTimeout(() => {
                handlePositsion();
            }, 200);
        }
        window.addEventListener('resize', resizeHandler)
        return () => {
            window.removeEventListener('resize', resizeHandler)
        }
    }, [componentId]);

    useEffect(() => {
        const elem = document.querySelector(`[data-component-id="${componentId}"]`);
        const observer = new ResizeObserver(() => {
            handlePositsion();
        })
        if (elem) {
            observer.observe(elem); // 观察元素的大小变化
        }
        return () => {
            observer.disconnect(); // 断开观察
        }
    }, [components])


    const el = useMemo(() => {
        return document.querySelector(`.${maskWrapper}`)!;
    }, [maskWrapper]);

    const handleDelete = () => {
        removeComponent(Number(componentId));
        // resetPosition();
        setCurComponent(null)
    }

    const cls = classNames(['absolute border-2 border-[#6366F1] rounded-md border-solid cursor-pointer shadow-lg'])


    return el ? createPortal((
        <>
            <div className={cls}
                style={{
                    pointerEvents: "none", // 除了指示该元素不是鼠标事件的目标之外，值none表示鼠标事件“穿透”该元素并且指定该元素“下面”的任何东西。
                    left: position.left + 'px',
                    top: position.top + 'px',
                    width: position.width + 'px',
                    height: position.height + 'px',
                    boxSizing: 'border-box',
                    zIndex: 12,
                }}>
            </div>
            <div className='absolute flex gap-2 w-full justify-end' style={{
                left: position.left + position.width + 'px',
                top: position.top + 'px',
                transform: 'translate(-100%, -100%)',
            }}>
                <div className='text-white bg-[#6366F1] text-xs px-3 rounded-sm '
                    style={{ zIndex: 13 }}
                >
                    {curComponet?.desc}
                </div>
                {
                    curComponet?.id !== 1 && <Popconfirm
                        title="提示"
                        description="确认要删除该组件吗？"
                        onConfirm={handleDelete}
                        onCancel={() => console.log('cancel')}
                        okText="Yes"
                        cancelText="No"
                    >
                        <div className='text-white bg-[#6366F1] text-xs px-3 rounded-sm' onClick={(e) => e.stopPropagation()}>
                            <i className='iconfont icon-shanchu'></i>
                        </div>
                    </Popconfirm>
                }


            </div>
        </>
    ), el) : null
};
export default ClickMask;
